package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
)

func upload(conn net.Conn, params []string) {

	// 文件信息
	fileName := params[0]
	fileSize, _ := strconv.Atoi(params[1])
	fmt.Println("fileName", fileName)
	fmt.Println("fileSize", fileSize)

	// 循环接收文件
	file, _ := os.OpenFile("uploads/"+fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
	writer := bufio.NewWriter(file)

	var readSize = 0
	for readSize < fileSize {
		data := make([]byte, 1024)
		n, _ := conn.Read(data) //   阻塞
		readSize += n
		// 将每行数据写入到文件writer中
		writer.WriteString(string(data[:n]))
		writer.Flush()
	}

	fmt.Println("文件上传成功")

}

func download(conn net.Conn, params []string) {

}

func main() {

	//  （1）服务端创建套接字对象socket
	sock, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("err", err)
	}
	// 关闭套接字
	defer sock.Close()

	for true {
		// （2）等待客户端链接
		fmt.Println("server is waiting...")
		conn, _ := sock.Accept()
		fmt.Println(conn)
		//（3）收发消息：conn.Read()  conn.Write()
		for true {

			infoBytes := make([]byte, 1024)
			n, _ := conn.Read(infoBytes)
			info := string(infoBytes[:n]) // "put a.png 12312"
			fmt.Println("info", info)
			infoSlice := strings.Split(info, " ")
			cmd := infoSlice[0]
			params := infoSlice[1:]
			fmt.Println("params", params)

			switch cmd {
			case "put":
				upload(conn, params)
			case "get":
				download(conn, params)

			}

		}

	}

}
